package com.paishen.peiniwan.module.message;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.util.DateUtils;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.util.LogUtil;
import com.paishen.common.widget.MaterialHeader;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

public class MainMessageLayout extends FrameLayout {

    private boolean loginError, isLogining;

    private final View layEmpty;
    private final PtrFrameLayout layPtrFrame;
    private final RecyclerView viewRecycler;
    private final ConversationAdapter adapter;

    public MainMessageLayout(Context context) {
        this(context, null);
    }

    public MainMessageLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.layout_main_profile_message, this);
        // ((ViewGroup) getChildAt(0)).getChildAt(0).setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);
        setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);

        viewRecycler = (RecyclerView) findViewById(R.id.view_recycler);
        viewRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        viewRecycler.setAdapter(adapter = new ConversationAdapter());
        viewRecycler.setItemAnimator(new DefaultItemAnimator());

        layPtrFrame = (PtrFrameLayout) findViewById(R.id.lay_ptr_frame);
        MaterialHeader header = new MaterialHeader(getContext());
        int[] colors = new int[]{0xFF05131A};
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        header.setPadding(0, BaseUtil.dip2px(15), 0, BaseUtil.dip2px(10));
        header.setPtrFrameLayout(layPtrFrame);
        layPtrFrame.setDurationToCloseHeader(1500);
        layPtrFrame.setHeaderView(header);
        layPtrFrame.addPtrUIHandler(header);
        layPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, viewRecycler, header);
            }

            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                if (loginError) {
                    loginEase();
                } else {
                    layPtrFrame.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_REFRESH_MAIN_MESSAGE_NEW_MESSAGE));
                        }
                    }, 1000);
                }
            }
        });

        layEmpty = findViewById(R.id.lay_empty);

        loginEase();
    }

    private void loginEase() {
        if (isLogining) return;
        isLogining = true;

        com.paishen.peiniwan.database.User login = App.i().getUser();
        String easemob_username = login.getEasemob_username();
        String easemob_password = login.getEasemob_password();
        EMClient.getInstance().login(easemob_username, easemob_password, new EMCallBack() {
            @Override
            public void onSuccess() {
                isLogining = false;
                LogUtil.d("EMChatManager onSuccess 登陆聊天服务器成功！");
                loginError = false;

                EMClient.getInstance().chatManager().loadAllConversations();
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().updateCurrentUserNick(App.i().getUser().getNickname());

                EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_REFRESH_MAIN_MESSAGE_NEW_MESSAGE));
            }

            @Override
            public void onProgress(int progress, String status) {
                LogUtil.d("EMChatManager onProgress 登陆中:" + progress + "#status:" + status);
            }

            @Override
            public void onError(int code, String message) {
                isLogining = false;
                LogUtil.d("EMChatManager onError 登陆聊天服务器失败！");
                loginError = true;

                // child thread -> ui thread layPtrFrame.refreshComplete();
                EventBus.getDefault().post(new BusEvent(BusEvent.ACTION_REFRESH_MAIN_MESSAGE_NEW_MESSAGE));
            }
        });
    }

    /**
     * 刷新页面
     * BusEvent.ACTION_REFRESH_MAIN_MESSAGE
     * 通过eventbus调用，顺带更新 mainLayout的未读数
     */
    public void refresh() {
        layPtrFrame.refreshComplete();

        List<EMConversation> data = loadConversationList();
        adapter.set(data);
        boolean emptyData = data == null || data.size() < 1;
        layEmpty.setVisibility(emptyData ? View.VISIBLE : View.GONE);
    }

    /**
     * 根据最后一条消息的时间排序
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {
                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
    }

    /**
     * 获取会话列表
     *
     * @return
     */
    protected List<EMConversation> loadConversationList() {
        // 获取所有会话，包括陌生人
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        // 过滤掉messages size为0的conversation
        /**
         * 如果在排序过程中有新消息收到，lastMsgTime会发生变化
         * 影响排序过程，Collection.sort会产生异常
         * 保证Conversation在Sort过程中最后一条消息的时间不变
         * 避免并发问题
         */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    //if(conversation.getType() != EMConversationType.ChatRoom){
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    //}
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }


    static class ConversationAdapter extends RecyclerView.Adapter<ConversationAdapter.ViewHolder> {
        protected List<EMConversation> conversationList = new ArrayList<>();

        public void set(List<EMConversation> dataList) {
            conversationList.clear();
            conversationList.addAll(dataList);
            notifyItemRangeChanged(0, getItemCount());
        }

        public class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
            public ViewHolder(View view) {
                super(view);
                view.setOnClickListener(this);
            }

            /**
             * 获取用户username或者群组groupid
             */
            String username;

            /**
             * 和谁的聊天记录
             */
            TextView name;
            /**
             * 消息未读数
             */
            TextView unreadLabel;
            /**
             * 最后一条消息的内容
             */
            TextView message;
            /**
             * 最后一条消息的时间
             */
            TextView time;
            /**
             * 用户头像
             */
            ImageView avatar;
            /**
             * 最后一条消息的发送状态
             */
            View msgState;
            /**
             * 整个list中每一行总布局
             */
            RelativeLayout list_itease_layout;

            @Override
            public void onClick(View v) {
                // demo中直接进入聊天页面，实际一般是进入用户详情页
                Intent intent = new Intent(v.getContext(), EaseChatActivity.class);
                intent.putExtra(EaseConstant.EXTRA_USER_ID, username);
                intent.putExtra(EaseChatFragment.EXTRA_OTHER_NICK, name.getText().toString());
                intent.putExtra(EaseChatFragment.EXTRA_SELF_NICK, App.i().getUser().getNickname());
                v.getContext().startActivity(intent);
            }
        }

        @Override
        public int getItemCount() {
            return conversationList.size();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_main_profile_message_chat_history, viewGroup, false);
            ViewHolder holder = new ViewHolder(view);
            holder.name = (TextView) view.findViewById(R.id.name);
            holder.unreadLabel = (TextView) view.findViewById(R.id.unread_msg_number);
            holder.message = (TextView) view.findViewById(R.id.message);
            holder.time = (TextView) view.findViewById(R.id.time);
            holder.avatar = (ImageView) view.findViewById(R.id.avatar);
            holder.msgState = view.findViewById(R.id.msg_state);
            holder.list_itease_layout = (RelativeLayout) view.findViewById(R.id.list_itease_layout);
            return holder;
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, final int position) {
            // 获取与此用户/群组的会话
            EMConversation conversation = conversationList.get(position);
            // 获取用户username或者群组groupid
            holder.username = conversation.getUserName();

            if (conversation.getType() == EMConversation.EMConversationType.GroupChat) {
                // 群聊消息，显示群聊头像
                holder.avatar.setImageResource(R.mipmap.ic_launcher1);
                EMGroup group = EMClient.getInstance().groupManager().getGroup(holder.username);
                holder.name.setText(group != null ? group.getGroupName() : holder.username);
            } else if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
                holder.avatar.setImageResource(R.mipmap.ic_launcher1);
                EMChatRoom room = EMClient.getInstance().chatroomManager().getChatRoom(holder.username);
                holder.name.setText(room != null && !TextUtils.isEmpty(room.getName()) ? room.getName() : holder.username);
            } else {
                EaseUserUtils.setUserAvatar(holder.itemView.getContext(), holder.username, holder.avatar);
                EaseUserUtils.setUserNick(holder.username, holder.name);
            }

            if (conversation.getUnreadMsgCount() > 0) {
                // 显示与此用户的消息未读数
                holder.unreadLabel.setText(String.valueOf(conversation.getUnreadMsgCount()));
                holder.unreadLabel.setVisibility(View.VISIBLE);
            } else {
                holder.unreadLabel.setVisibility(View.INVISIBLE);
            }

            if (conversation.getAllMsgCount() != 0) {
                // 把最后一条消息的内容作为item的message内容
                EMMessage lastMessage = conversation.getLastMessage();
                holder.message.setText(EaseSmileUtils.getSmiledText(holder.itemView.getContext(), EaseCommonUtils.getMessageDigest(lastMessage, (holder.itemView.getContext()))),
                        TextView.BufferType.SPANNABLE);

                holder.time.setText(DateUtils.getTimestampString(new Date(lastMessage.getMsgTime())));
                if (lastMessage.direct() == EMMessage.Direct.SEND && lastMessage.status() == EMMessage.Status.FAIL) {
                    holder.msgState.setVisibility(View.VISIBLE);
                } else {
                    holder.msgState.setVisibility(View.GONE);
                }
            }
        }
    }
}
